package db

import (
	accountQuery "content_system/dao/def/account/query"
	contentQuery "content_system/dao/def/content/query"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
)

var (
	once         sync.Once
	AccountDB    *gorm.DB
	AccountQuery *accountQuery.Query
	ContentDB    *gorm.DB
	ContentQuery *contentQuery.Query
)

func Init() {
	once.Do(func() {
		AccountDB = ConnectDB()
		AccountQuery = accountQuery.Use(AccountDB)
		ContentDB = ConnectContentDB()
		ContentQuery = contentQuery.Use(ContentDB)
	})
}

func ConnectDB() (conn *gorm.DB) {
	var err error
	dsn := "root:mysql_GSjWzR@tcp(127.0.0.1:3306)/cms_account?charset=utf8mb4&parseTime=True&loc=Local"
	// 建立连接
	connect, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	connect = connect.Debug()
	db, err := connect.DB()
	if err != nil {
		panic(err)
	}
	db.SetMaxIdleConns(5)
	db.SetMaxOpenConns(10)

	return connect
}

func ConnectContentDB() (conn *gorm.DB) {
	var err error
	dsn := "root:mysql_GSjWzR@tcp(127.0.0.1:3306)/cms_content?charset=utf8mb4&parseTime=True&loc=Local"
	// 建立连接
	connect, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	connect = connect.Debug()
	db, err := connect.DB()
	if err != nil {
		panic(err)
	}
	db.SetMaxIdleConns(5)
	db.SetMaxOpenConns(10)

	return connect
}
